package mysql

import (
	"gorm.io/gorm"
	"week_three/car_srv/models"
)

func CreateCar(car *models.Car) (*models.Car, *gorm.DB, error) {
	var tx *gorm.DB
	return car, tx, models.InitMysql(func(DB *gorm.DB) error {
		tx = DB.Begin()
		return tx.Create(&car).Error
	})
}
func MysqlToReids() ([]*models.Car, error) {
	var cars []*models.Car
	return cars, models.InitMysql(func(DB *gorm.DB) error {
		return DB.Order("price desc").Find(&cars).Error
	})
}

func GetCarTypeAll(pid uint) ([]*models.CarType, error) {
	var CarList []*models.CarType
	err := models.InitMysql(func(DB *gorm.DB) error {
		return DB.Where("pid = ?", pid).Preload("Cars").Find(&CarList).Error
	})
	if err != nil {
		return CarList, err
	}
	for _, v := range CarList {
		list, err := GetCarTypeAll(v.ID)
		if err != nil {
			return CarList, err
		}
		v.Cars = list
	}

	return CarList, nil
}
